import Vue from 'vue'
import axios from 'axios'
import { VueAxios } from './axios'
import { Dialog, Toast } from 'vant'
import store from '@/Vuex/index'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.API_BASE_URL,
  timeout: 30000, // 请求超时时间
})

const service_baojie = axios.create({
  baseURL: process.env.BAOJIE_API_BASE_URL,
  timeout: 30000, // 请求超时时间
})

Toast.allowMultiple()
let requestToast = null

const err = (error) => {
  requestToast ? requestToast.clear() : ''
  if (error.message.includes('timeout')) {
    Dialog.alert({
      title: '提示',
      message: '连接超时',
    })
  }
  if (error.message.includes('Network')) {
    Dialog.alert({
      title: '提示',
      message: '网络异常',
    })
    return Promise.reject('网络异常')
  }
  return Promise.reject(error)
}
const beforeRequest = config => {
  console.log(config)
  if ((config.data && config.data['noLoading']) || (config.params && config.params['noLoading'])) {

  } else {
    requestToast ? requestToast.clear() : ''
    requestToast = Toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    });
    console.log(requestToast)
  }
  config.headers['token'] = store.state.token
  if (config.method == 'post') {
    config.data['token'] = store.state.token
  } else if (config.method == 'get') {
    config.params['token'] = store.state.token
  }
  return config
}

const afterResponse = (response) => {
  requestToast ? requestToast.clear() : ''
  console.log(response)
  store.commit('SAVE_SERVER_TIME', new Date(response.headers.date))
  if (response.data.code && response.data.code == '0000') {
    if (response.data.data) {
      return response.data.data
    } else {
      return response.data
    }
  } else if (response.data.code && response.data.code == '18009') {
    store.commit('SAVE_REQUEST_PARAMS', {
      token: response.data.data
    })
    store.commit('SEND_TOKEN_TO_APP', {
      token: response.data.data
    })
    return Promise.reject('18009')
  }
   else {
    throw new Error(response.data.msg)
  }
}

// request interceptor
service.interceptors.request.use(beforeRequest, err)
service_baojie.interceptors.request.use(beforeRequest, err)

// response interceptor
service.interceptors.response.use(afterResponse, err)
service_baojie.interceptors.response.use(afterResponse, err)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service, service_baojie)
  }
}

export {
  installer as VueAxios,
  service as axios,
  service_baojie as axios_baojie
}
